package com.work.example.demo5.service.impl;

import java.util.Date;
import java.util.List;

import com.work.example.demo5.domain.SecurityUser;
import com.work.example.demo5.domain.UserEntity;
import com.work.example.demo5.repo.UserEntityRepository;
import com.work.example.demo5.service.UserEntityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class UserEntityServiceImpl implements UserEntityService, UserDetailsService {
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    UserEntityRepository userEntityRepository;
    @Override
    public UserEntity getUserByName(String username) {
        return userEntityRepository.getUserByName(username);
    }

    @Override
    public UserEntity saveUser(UserEntity entity) {
        if (null == entity.getCreateTime()) {
            entity.setCreateTime(new Date());
        }
        entity.setPassword(passwordEncoder.encode(entity.getPassword()));
        UserEntity user = userEntityRepository.getUserByName(entity.getUsername());
        if (null == user) {
            userEntityRepository.save(entity);
            user = entity;
        }
        return user;
    }
    public List<UserEntity>getUsers(){
        List<UserEntity> uList = userEntityRepository.findAll();
        return uList;
    }

    @Override
    public Long getUserId(String username) {
        return userEntityRepository.getUserId(username);
    }

    public int updateUser(UserEntity user) {
        return userEntityRepository.modifyById(user.getUsername(),user.getId().intValue());

    }
    public void deleteUser(UserEntity user) {
        userEntityRepository.deleteById(user.getId().intValue());
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserEntity userEntity = getUserByName(username);
        if (null == userEntity)
            throw new UsernameNotFoundException("用户不存在");
        return new SecurityUser(userEntity);
    }
}